package xin.petstore.framework.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegexpUtil {


    public static String analysisParambyKey(String pattern, String key, String info) {
        if (info.contains(key)) {
            return analysisParambyKey(pattern, key, info, 1);
        }
        return "";
    }

    /**
     * @param pattern
     * @param key
     * @param info
     * @return
     */
    public static String analysisParambyKey(String pattern, String key, String info, int index) {
        if (info.contains(key)) {
            return analysisParam(pattern, info, index);
        }
        return "";
    }

    /**
     * @param pattern
     * @param info
     * @return
     */
    public static String analysisParam(String pattern, String info, int index) {
        final Matcher matcher = Pattern.compile(pattern).matcher(info);
        if (matcher.matches()) {
            return matcher.group(index);
        }
        return "";
    }

    /**
     * 拼接解析参数以及解析代码
     *
     * @param
     * @param info
     * @return
     */
    public static String analysisURLParam(String param, String info) {
        if (info.contains(param)) {
            StringBuffer sb = new StringBuffer();
            sb.append(".*");
            sb.append(param);
            sb.append("=(.*?)&.*");
            String result = analysisParam(sb.toString(), info, 1);
            if (result.isEmpty()) {
                sb.setLength(0);
                sb.append(".*");
                sb.append(param);
                sb.append("=(.*)");
                result = analysisParam(sb.toString(), info, 1);
            }
            return result;
        }
        return "";
    }

    public static void main(String[] args) {
        String url = "http://activity.petstore.xin/html/834eeff8-0f77-4864-ad46-08d6a30d5a6a.html?ch_sign=dsfwz&act_sign=XSHBHD&pkey=3YBLeqZKonIvpGUIkDVWT9dCR11EUHgB";
        System.out.println(analysisURLParam("ch_sign", url));
    }

}
